<template>
  <div class="box">
    <van-search placeholder="请输入商品的名字" @focus="$router.push('goods/search')" />
    <van-tree-select :items="category" :main-active-index.sync="active" class="tree">
      <template #content>
        <div id="sbu-cate">
          <!--绑定点击事件传id过去-->
          <div class="item" v-for="(item,index) in gitCat" :key="index" @click="gotoCate(item.id)">
            <img :src="item.icon" />
            <p>{{item.name}}</p>
          </div>
        </div>
      </template>
    </van-tree-select>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      active: 0,
      category: [{ text: "所有分类", id: 0 }],
      goodslist: []
    };
  },
  computed: {
    gitCat() {
      let data = this.goodslist;
      //如果当前的值是0的话
      if (this.active == 0) {
        return data;
      }
      //当前选中商品分类的id
      let id = this.category[this.active].id;
      // console.log(id);
      return data.filter(item => {
        return item.pid == id;
      });
    }
  },
  methods: {
    //获取分类列表的数据
    getCategory() {
      this.$axios
        .get("https://api.it120.cc/small4/shop/goods/category/all")
        .then(res => {
          // console.log(res);
          //渲染页面
          this.goodslist = res.data;
          //便利所有的商品分类,然后找出pid==0的商品
          let data = res.data.forEach(item => {
            if (item.pid == 0) {
              //顶级分类
              //实例化对象
              let object = new Object();
              object.id = item.id;
              object.text = item.name;
              this.category.push(object);
            }
          });
          this.goodslist = res.data;
        });
    },
    //传id
    gotoCate(cid) {
      this.$router.push("/goods/cate/" + cid);
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.getCategory();
  }
};
</script>
<style scoped lang="scss">
.box {
  width: 100%;
  .tree {
    height: 100% !important;
    #sbu-cate {
      width: 100%;
      max-height: 85%;
      display: flex;
      flex-wrap: wrap;
      text-align: center;
      .item {
        width: 31%;
        margin: 1%;
        img {
          width: 98%;
        }
        p {
          line-height: 0.6rem;
        }
      }
    }
  }
}
</style>